package com.github.freegeese.plugins.pdf.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Cmds {
    private List<String> cmdLines = new ArrayList<>();
    private String charset = "gb2312";

    public static Cmds cmd(String... cmds) {
        Cmds cmd = new Cmds();
        cmd.cmdLines.addAll(Arrays.asList(cmds));
        return cmd;
    }

    public Cmds charset(String charset) {
        this.charset = charset;
        return this;
    }

    public List<String> exec() {
        return exec(false);
    }

    public void execAsync() {
        exec(true);
    }

    private List<String> exec(boolean async) {
        List<String> results = new ArrayList<>();
        try {
            Process p = Runtime.getRuntime().exec(cmdLines.toArray(new String[0]));
            final BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream(), charset));
            final BufferedReader inputReader = new BufferedReader(new InputStreamReader(p.getInputStream(), charset));
            if (async) {
                List<BufferedReader> readers = Arrays.asList(inputReader, errorReader);
                for (BufferedReader reader : readers) {
                    new Thread() {
                        @Override
                        public void run() {
                            String line;
                            try {
                                while (null != (line = reader.readLine())) {
                                    System.out.println(line);
                                }
                                reader.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                }
            } else {
                String inputLine;
                while (null != (inputLine = inputReader.readLine())) {
                    System.out.println(inputLine);
                    results.add(inputLine);
                }
                String errorLine;
                while (null != (errorLine = errorReader.readLine())) {
                    System.out.println(errorLine);
                    results.add(inputLine);
                }
                inputReader.close();
                errorReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return results;
    }
}
